#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import cgi

from bible.TheHolyBible import *
import bible.util.HolyBibleFetch

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util

# @action /data/versions
class Versions(webapp.RequestHandler):
  def get(self):
    controller = BibleController()
    versions = controller.getVersions()
    template_values = {
      'versions' : versions
    }
    template_path = os.path.join(os.path.dirname(__file__), "../template/data/versions")
    self.response.out.write(template.render(template_path, template_values))

# @action /data/books
class Books(webapp.RequestHandler):
  def get(self):
    vcode = cgi.escape(self.request.get('vcode'))

    controller = BibleController()
    books = controller.getBooks(vcode)
    #books = bible.util.HolyBibleFetch.getBooks(self, vcode)
    template_values = {
      'books' : books
    }
    template_path = os.path.join(os.path.dirname(__file__), "../template/data/books")
    self.response.out.write(template.render(template_path, template_values))


# @action /data/chapters
class Chapters(webapp.RequestHandler):
  def get(self):

    bcode = (int)(cgi.escape(self.request.get('bcode')))

    controller = BibleController()
    chapters = controller.getChapters(bcode)

    template_path = os.path.join(os.path.dirname(__file__), "../template/data/datas")
    self.response.out.write(json.dumps(chapters))


# @action /data/verses
class Verses(webapp.RequestHandler):
  def get(self):
    vcode = cgi.escape(self.request.get('vcode'))
    bcode = (int)(cgi.escape(self.request.get('bcode')))
    cnum = (int)(cgi.escape(self.request.get('cnum')))

    if vcode == "": vcode = "GAE"
    if bcode == "": bcode = "1"
    if cnum == "": cnum = "1"

    controller = BibleController()
    verses = controller.getVerses(vcode, bcode, cnum)

    template_values = {
      'verses': verses
    }
    template_path = os.path.join(os.path.dirname(__file__), "../template/data/verses")
    self.response.out.write(template.render(template_path, template_values))


def main():
  application = webapp.WSGIApplication([('/data/versions', Versions)
                                        , ('/data/chapters', Chapters)
                                        , ('/data/books', Books)
                                        , ('/data/verses', Verses)],
                                       debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
